<?php

namespace app\personal\controller;

use app\admin\service\NodeService;
use app\personal\service\PersonService;
use app\admin\service\PointService;
use app\admin\service\CompanyService as AdminComService;
use app\admin\service\ArchivesService;
use app\mobile\validate\Company as CompanyValidate;
use app\admin\service\MemberService;
use app\common\service\WxTokenService;
use library\Controller;
use think\Db;

/**
 * 登录
 * Class Login
 * @package app\personal\controller
 */
class Login extends Controller
{
    /**
     * 登录
     */
    public function index()
    {
        if ($this->request->isGet()) {      	
            $isLogin = PersonService::IsLogin();
            if ($isLogin) {
                $this->redirect('personal/index/index');
            } else {
                $this->loginskey = session('loginskey');
                if (empty($this->loginskey)) {
                    $this->loginskey = uniqid();
                    session('loginskey', $this->loginskey);
                }
                $this->fetch();
            }
        } else {
        	$params = $this->request->post();
        	if(empty($params['verify'])){
        		//身份证密码登录  
        		$data = $this->_input([
	                'username' => trim($this->request->post('username')),
	                'password' => trim($this->request->post('password')),
	                'platform' => trim($this->request->post('platform')),
	            ], [
	                'username' => 'require|min:6',
	                'password' => 'require|min:6',
	                'platform' => 'require|in:1,2',
	            ], [
	                'username.require' => '登录账号不能为空！',
	                'password.require' => '登录密码不能为空！',
	                'username.min' => '登录账号长度不能少于6位有效字符！',
	                'password.min' => '登录密码长度不能少于6位有效字符！',
	                'platform.in' => '登录平台数值错误',
	            ]);
	            
	            $map = ['loginname' => $data['username'], 'type' => 2];
	            $user = Db::name('SystemMember')->where($map)->find();
	            if (empty($user)) $this->error('未查询到相关信息，请重新输入!');
	            if ($user['status'] != 1) $this->error('账号已经被禁用，请联系客服!');
	            // 账号锁定消息
	            $cache = cache("user_login_{$user['loginname']}");
	            if (is_array($cache) && !empty($cache['number']) && !empty($cache['time'])) {
	                if ($cache['number'] >= 10 && ($diff = $cache['time'] + 3600 - time()) > 0) {
	                    list($m, $s, $info) = [floor($diff / 60), floor($diff % 60), ''];
	                    if ($m > 0) $info = "{$m} 分";
	                    $this->error("<strong class='color-red'>抱歉，该账号已经被锁定！</strong><p class='nowrap'>连续 10 次登录错误，请 {$info} {$s} 秒后再登录！</p>");
	                }
	            }
	            if (md5($user['password'] . session('loginskey')) !== $data['password']) {
	                if (empty($cache) || empty($cache['time']) || empty($cache['number']) || $cache['time'] + 3600 < time()) {
	                    $cache = ['time' => time(), 'number' => 1, 'geoip' => $this->request->ip()];
	                } elseif ($cache['number'] + 1 <= 10) {
	                    $cache = ['time' => time(), 'number' => $cache['number'] + 1, 'geoip' => $this->request->ip()];
	                }
	                cache("user_login_{$user['loginname']}", $cache);
	                if (($diff = 10 - $cache['number']) > 0) {
	                    $this->error("<strong class='color-red'>登录账号或密码错误！</strong><p class='nowrap'>还有 {$diff} 次尝试机会，将锁定一小时内禁止登录！</p>");
	                } else {
	                    sysoplog('系统管理', "账号{$user['loginname']}连续10次登录密码错误，请注意账号安全！");
	                    $this->error("<strong class='color-red'>登录账号或密码错误！</strong><p class='nowrap'>尝试次数达到上限，锁定一小时内禁止登录！</p>");
	                }
	            }
	            // 登录成功并更新账号
	            cache("user_login_{$user['loginname']}", null);
	            Db::name('SystemMember')->where(['id' => $user['id']])->update([
	                'login_at' => time(), 'login_ip' => $this->request->ip(), 'login_source' => 2,'login_num' => Db::raw('login_num+1'),
	            ]);
				session('loginskey', null);
	            session('member', $user);
	            sysoplog('用户登陆', '用户登录系统成功');
//	            $this->success('登录成功，正在进入系统...', url('personal/index/index'));
				$scheme = $_SERVER['REQUEST_SCHEME'] == 'http' ? 'http://' : 'https://';
	            $index_url = $scheme . $_SERVER['SERVER_NAME'] . '/personal/index/index';			
	            if($data['platform'] == 1){
	            	//微信内需要获取openid，先组装url获取code				
					$wxtoken = new WxTokenService();
					$baseUrl = urlencode($index_url);
					$url = $wxtoken->__CreateOauthUrlForCode($baseUrl,'STATE');
		            $this->success('微信内部环境', ['url'=>$url]);
	            }else{           	
	            	$this->success('微信外部环境', ['url'=>$index_url]);
	            }
        	}else{
        		//手机号验证码登录  
        		$data = $this->_input([
	                'mobile' => trim($this->request->post('mobile')),
	                'verify' => trim($this->request->post('verify')),
	                'platform' => trim($this->request->post('platform')),
	            ], [
	                'mobile' => 'require|mobile',
	                'verify' => 'require|number|length:4',
	                'platform' => 'require|in:1,2',
	            ], [
	                'mobile.require' => '手机号必须填写',
	                'mobile.mobile' => '手机号格式错误',
	                'verify.require' => '验证码必须填写',
	                'verify.number' => '验证码格式错误',
	                'verify.length' => '验证码为4位',
	                'platform.in' => '登录平台数值错误',
	            ]);
	            $map = ['mobile' => $data['mobile'], 'type' => 2];
	            $user = Db::name('SystemMember')->where($map)->find();
	            if (empty($user)) $this->error('未查询到相关信息，请重新输入!');
	            if ($user['status'] != 1) $this->error('账号已经被禁用，请联系客服!');
	            $verify = Db::name('system_verify')
						->where(['mobile'=>$data['mobile'],'status'=>0,'type'=>2])
						->order('create_at desc')
						->find();
				if(!$verify || $data['verify'] != $verify['code']){
					$this->error('验证码错误');
				}		
				if(time() - $verify['create_at'] > 900){
					$this->error('验证码已失效');
				}
				// 登录成功并更新账号
	            cache("user_login_{$user['loginname']}", null);
	            Db::name('SystemMember')->where(['id' => $user['id']])->update([
	                'login_at' => time(), 'login_ip' => $this->request->ip(), 'login_source' => 2,'login_num' => Db::raw('login_num+1'),
	            ]);
	            Db::name('system_verify')->where(['mobile'=>$data['mobile'],'code'=>$data['verify'],'type'=>2])->update(['status'=>1]);
				session('loginskey', null);
	            session('member', $user);
	            sysoplog('用户登陆', '用户登录系统成功');
//	            $this->success('登录成功，正在进入系统...', url('personal/index/index'));	
				$scheme = $_SERVER['REQUEST_SCHEME'] == 'http' ? 'http://' : 'https://';
	            $index_url = $scheme . $_SERVER['SERVER_NAME'] . '/personal/index/index';			
	            if($data['platform'] == 1){
	            	//微信内需要获取openid，先组装url获取code				
					$wxtoken = new WxTokenService();
					$baseUrl = urlencode($index_url);
					$url = $wxtoken->__CreateOauthUrlForCode($baseUrl,'STATE');
		            $this->success('微信内部环境', ['url'=>$url]);
	            }else{           	
	            	$this->success('微信外部环境', ['url'=>$index_url]);
	            }
        	}
            
        }

    }
    
    
     //发送短信
    public function send_sms(){
    	$data = $this->request->post();
    	//检测验证码
    	trim_array($data);
		if(empty($data['mobile']) || !$data['mobile']){
			$this->error('请输入手机号!');
		}
		if(!isMobile($data['mobile'])){
			$this->error('手机号格式错误!');
		}
		if(empty($data['type']) || !$data['type']){
			$this->error('用户类型错误!');
		}
		if(empty($data['verify_type']) || !$data['verify_type']){
			$this->error('验证类型错误!');
		}
		//查找该手机是否120S内发送过
//		$verify = Db::name('system_verify')->where(['mobile'=>$data['mobile'],'type'=>$data['type'],'status'=>0])->order('create_at desc')->find();
//		if(time() - $verify['create_at'] < 120){
//			$this->error('短信发送过于频繁!');
//		}
		//生成随机验证码
		$code = rand(1000,9999);
		
    	switch($data['verify_type']){
            case '1':  //注册
            	$user = Db::name('SystemMember')->where(['mobile'=>$data['mobile'],'type'=>$data['type']])->find();
            	if($user){
            		$this->error('手机号已注册');
            	}
                $result = sms_verify($data['mobile'],'','reg',$code);
                break;
            case '2':  //登录
            	$user = Db::name('SystemMember')->where(['mobile'=>$data['mobile'],'type'=>$data['type']])->find();
            	if(!$user){
            		$this->error('手机号未注册');
            	}
                $result = sms_verify($data['mobile'],'','login',$code);
                break;
            case '3': //找回密码
            	$user = Db::name('SystemMember')->where(['mobile'=>$data['mobile'],'type'=>$data['type']])->find();
            	if(!$user){
            		$this->error('手机号未注册');
            	}
                $result = sms_verify($data['mobile'],'','pwd',$code);
                break;
            case '4': //修改手机
            	$user = Db::name('SystemMember')->where(['mobile'=>$data['mobile'],'type'=>$data['type']])->find();
            	if($user){
            		$this->error('手机号已注册');
            	}
                $result = sms_verify($data['mobile'],'','change',$code);
                break;
            default:     //身份验证
                $result = sms_verify($data['mobile'],'','identity',$code);
        }
		if($result['Code'] == 'OK'){
			Db::name('system_verify')->insert(['mobile'=>$data['mobile'],'code'=>$code,'type'=>$data['verify_type'],'create_at'=>time()]);
			$this->success('发送成功');
		}else{
			$this->error('发送失败，请稍后再试');
		}
    }


    /**
     * 退出
     */
    public function logout()
    {
        \think\facade\Session::clear();
        \think\facade\Session::destroy();
        $this->redirect('@personal/login');
    }
    
    
    /**
     * 协议
     */
    public function agreement()
    {
    	$this->user_agreement = Db::name('system_agreement')->where(['id'=>2])->value('content');
    	$this->fetch();
    }
 
}
